<template>
  <div class="app-container">
    <div ref="search" class="filter-container">
      <el-button v-if="isWindow" icon="el-icon-refresh" @click.stop="refresh">刷新</el-button>
      <el-input v-if="isWindow" v-model.trim="pageData.fileNameSearch" clearable placeholder="输入附件名" :clearable="true" @keyup.enter.native="search" @clear="search" />
      <el-button v-if="isWindow" type="primary" icon="el-icon-search" @click.stop="search">查询</el-button>
      <el-upload
        v-show="false"
        ref="upload"
        class="uploadFileClass"
        accept=".xlsx, .xls, .csv,.docx,.doc,.pdf,.png,.jpg,.jpeg"
        multiple
        action="#"
        :limit="5"
        :show-file-list="false"
        :auto-upload="false"
        :on-exceed="onExceed"
        :on-change="onChange"
      />
      <el-button v-if="isWindow" type="danger" icon="el-icon-upload2" @click.stop="addFile">添加</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="loading"
      :data="list"
      stripe
      border
      border
      :height="tableHeight"
      :class="{'innerTable':!isWindow}"
      @sort-change="sortChange"
    >
      <el-table-column label="序号" type="index" width="50" align="center" :index="index" />
      <el-table-column label="操作" fixed="right" width="220px">
        <template slot-scope="{row}">
          <el-button size="mini" @click.stop="preview(row)">预览</el-button>
          <el-button size="mini" @click.stop="download(row)">下载</el-button>
          <el-button size="mini" @click.stop="remove(row)">{{ isWindow?'删除':'移除' }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="文件名"
        prop="name"
        sortable="custom"
        :sort-orders="['ascending','descending']"
      />
      <el-table-column
        align="center"
        label="文件大小"
        sortable="custom"
        prop="size"
        :sort-orders="['ascending','descending']"
      >
        <template slot-scope="scope">
          {{ scope.row.size | renderSize }}
        </template>
      </el-table-column>
    </el-table>
    <pagination v-if="tableId" v-show="total>0" :total="total" :page.sync="pageData.pageCode" :limit.sync="pageData.pageSize" @pagination="getList" />
    <div v-show="false" v-viewer="options" class="images clearfix">
      <div class="block">
        <el-image
          style="width: 100px; height: 100px"
          :src="picUrl"
          fit="fill"
          :alt="picName"
        />
      </div>
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 分页
import { sortByProp } from '@/utils/tool'
import { downloadFile, getFileUrl, getList1, deleteById } from '@/api/gc_manage/fileManage/fileManage'
import uploadFile from '@/views/common/uploadFile'
export default {
  name: 'FileManager',
  components: { Pagination },
  props: {
    // 自动添加一个key为layerid的值， 该值为创建层的id
    layerid: {
      type: String,
      required: false
    },
    tHeight: {
      type: Number,
      required: false
    },
    isWindow: { // 是否为弹出窗口
      type: Boolean,
      default: true
    },
    tableId: {
      type: String,
      required: false
    },
    tableName: {
      type: String,
      required: false
    }
  },
  data() {
    return {
      options: {
        toolbar: {
          zoomIn: {
            show: 4,
            size: 'large'
          },
          zoomOut: {
            show: 4,
            size: 'large'
          },
          oneToOne: {
            show: 4,
            size: 'large'
          },
          reset: {
            show: 4,
            size: 'large'
          },
          prev: {
            show: 4,
            size: 'large'
          },
          play: {
            show: 4,
            size: 'large'
          },
          next: {
            show: 4,
            size: 'large'
          },
          rotateLeft: {
            show: 4,
            size: 'large'
          },
          rotateRight: {
            show: 4,
            size: 'large'
          },
          flipHorizontal: {
            show: 4,
            size: 'large'
          },
          flipVertical: {
            show: 4,
            size: 'large'
          }
        }
      },
      picUrl: undefined, picName: undefined,
      top: undefined, // 顶层组件
      pageData: {
        pageCode: 1,
        pageSize: 10,
        fileNameSearch: undefined
      },
      loading: false,
      files: new Set(),
      list: [], total: 0,
      tableHeight: this.tHeight || 450 // 表格高度
    }
  },
  watch: {
    list(val) {
      this.$emit('filesChange', val)
    }
  },
  mounted() {
    this.$store.commit('app/SET_LAYERID', this.layerid)
    this.top = this.$parent
    while (this.top && !this.top.showDialog) {
      this.top = this.top.$parent
    }
    if (this.tableId) {
      this.getList()
    }
  },
  methods: {
    index(index) {
      return (this.pageData.pageCode - 1) * this.pageData.pageSize + index + 1
    },
    getList() {
      this.loading = true
      this.$set(this.pageData, 'tableId', this.tableId)
      getList1(this.pageData).then(res => {
        if (res) {
          this.list = res.data
          this.total = res.total
        }
      }).finally(() => {
        this.loading = false
      })
    },
    refresh() {
      this.$delete(this.pageData, 'fileNameSearch')
      this.pageData.pageCode = 1// 重置当前页为第一页
      this.getList()
    },
    search() {
      this.pageData.pageCode = 1// 重置当前页为第一页
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (!this.tableId) { // 新增
        this.list.sort(sortByProp(prop, order))
        return
      }
      if (order) {
        this.sortByID(order, prop)
      } else {
        delete this.pageData.order
        delete this.pageData.prop
        this.search()
      }
    },
    sortByID(order, prop) {
      if (order === 'ascending') {
        this.pageData.order = 'asc'
      } else {
        this.pageData.order = 'desc'
      }
      this.pageData.prop = prop
      this.search()
    },
    onExceed() {
      this.$message({
        message: '一次最多只能上传5个文件',
        type: 'warning',
        duration: 1000
      })
    },
    onChange(file) {
      // 不能超过限制大小
      if (file.size / 1024 / 1024 > 100) {
        this.$refs.upload.uploadFiles.splice(this.$refs.upload.uploadFiles.indexOf(file), 1)
        this.$message({
          message: '上传文件超过最大限制100MB',
          type: 'warning',
          duration: 1000
        })
      }
      if (!this.files.has(file.name)) {
        this.files.add(file.name)
        this.list.push(file)
      }
    },
    addFile() {
      if (this.tableId) {
        this.$layer.iframe({
          content: {
            content: uploadFile, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              tableId: this.tableId,
              tableName: this.tableName
            }// props
          },
          area: ['800px', '500px'],
          shadeClose: false,
          title: '上传附件' // 标题
        })
        return
      }
      this.$refs.upload.$children[0].$refs.input.click()
    },
    remove(row) {
      if (this.tableId) {
        this.$confirm('是否确认删除?', '删除确认', {
          confirmButtonText: '确 定',
          cancelButtonText: '取 消',
          cancelButtonClass: 'cancelClass',
          type: 'warning'
        }).then(() => {
          this.loading = true
          deleteById({ fuId: row.fuId, fileSaveName: row.fileSaveName }).then(res => {
            if (res && res.result === 'success') {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1000
              })
              this.getList()
            }
          }).finally(() => {
            this.loading = false
          })
        }).catch(() => {
          this.$message({
            message: '操作已取消',
            type: 'info',
            duration: 1000
          })
        })
        return
      }
      this.list.splice(this.list.indexOf(row), 1)
      this.$refs.upload.uploadFiles.splice(this.$refs.upload.uploadFiles.indexOf(row), 1)
      this.files.delete(row.name)
    },
    preview(row) {
      const _this = this
      const previewData = {
        picUrl: '',
        picName: row.name,
        type: row.name.split('.')[row.name.split('.').length - 1].toLowerCase()
      }
      if (row.fuId) {
        // 已保存的文件,从后台拿url
        getFileUrl({ name: row.fileSaveName }).then(res => {
          if (res.result === 'success') {
            previewData.picUrl = res.url
            _this.doPreview(previewData)
          }
        })
      } else {
        const reader = new FileReader()
        reader.readAsDataURL(row.raw)
        reader.onload = function() {
          previewData.picUrl = reader.result
          _this.doPreview(previewData)
        }
      }
    },
    doPreview(data) {
      switch (data.type) {
        case 'png':
        case 'jpg':
        case 'bmp':
        case 'gif':
        case 'svg':
          this.picUrl = data.picUrl
          this.picName = data.picName
          this.$el.querySelector('.images').$viewer.show()
          break
        case 'doc':
        case 'docx':
        case 'pdf':
        // case 'xls':
        // case 'xlsx':
          this.top.showDialog(data.picUrl, data.type)
          break
        default:
      }
    },
    // 下载
    download(row) {
      let blob = null
      let objectUrl = null
      const link = document.createElement('a')
      new Promise(resolve => {
        if (row.fuId) {
          return downloadFile(row).then(res => {
            resolve(res)
          })
        } else {
          blob = new Blob([row.raw])
          resolve()
        }
      }).then(res => {
        if (res) {
          console.log(res)
          blob = new Blob([res.data])
        }
        objectUrl = URL.createObjectURL(blob) // 创建URL
        link.href = objectUrl
        link.download = row.name // 自定义文件名
        link.click() // 下载文件
      }).finally(() => {
        if (objectUrl) {
          URL.revokeObjectURL(objectUrl) // 释放内存
        }
      })
    }
  }
}
</script>
<style scoped>

</style>
